package com.msa.data;

/**
 * @author 毕子航 951755883@qq.com
 * @date 2018/12/21
 */
public class MyArray<T> {
	Object[] arr;
	int elements;

	public MyArray(int element) {
		this.arr = new Object[element];
		this.elements = 0;
	}

	/**
	 * 增加元素
	 *
	 * @param element
	 */
	public void add(T element) {
		check();
		arr[elements] = element;
		elements++;
	}

	/**
	 * 打印数据
	 */
	public void display() {
		System.out.print("[");
		for (int i = 0; i < elements; i++) {
			System.out.print(i + "=" + arr[i] + " ");
		}
		System.out.print("]");
		System.out.println();
	}

	/**
	 * 更新
	 *
	 * @param index
	 * @param value
	 */
	public void set(int index, T value) {
		check(index);
		arr[index] = value;
	}

	/**
	 * 删除
	 *
	 * @param index
	 */
	public void remove(int index) {
		check(index);
		int last = elements - 1;
		if (index != last) {
			for (int i = index; i < last; i++) {
				arr[i] = arr[i + 1];
			}
		}
		elements--;
	}

	/**
	 * 清空
	 */
	public void clear() {
		elements = 0;
		arr = new Object[arr.length];
	}

	/**
	 * 查询某一个元素
	 *
	 * @param index
	 * @return
	 */
	public T get(int index) {
		check(index);
		return (T) arr[index];
	}

	/**
	 * 查询某个值的下标
	 *
	 * @param value
	 * @return
	 */
	public int indexOf(T value) {
		for (int i = 0; i < elements; i++) {
			if (arr[i].equals(value)) {
				return i;
			}
		}
		return -1;
	}

	/**
	 * 获取实际大小
	 *
	 * @return
	 */
	public int size() {
		return elements;
	}

	private void throwException() {
		throw new ArrayIndexOutOfBoundsException("容器大小不足");
	}

	/**
	 * 检查数组是否越界
	 *
	 * @throws ArrayIndexOutOfBoundsException
	 */
	private void check() throws ArrayIndexOutOfBoundsException {
		if (elements > arr.length) {
			throwException();
		}
	}


	/**
	 * 检查下标是否越界
	 *
	 * @param index
	 * @throws ArrayIndexOutOfBoundsException
	 */
	private void check(int index) throws ArrayIndexOutOfBoundsException {
		check();
		if (index >= elements) {
			throwException();
		}
	}

	public static MyArray newArray(int size) {
		return new MyArray(size);
	}
}
